const socket_mongo = require('./socket_mongo')
module.exports = (io) => {
    var users = {}
    var num = 0
    io.on("connection", (socket) => {
        // 用户登录
        socket.on('login', async (userId) => {
            console.log('userid', userId);
            // socket.name => 用户id
            socket.name = userId
            users[userId] = socket.id
            socket.emit('login', socket.id)
            num += 1
            console.log('==============进入=============');
            // console.log('userId', userId);
            // console.log('用户连接', socket.id);
            console.log('在线人数', num);
            console.log('===============================');
        })

        // 一对一消息(private_chat)
        socket.on('private_chat', async (dataMsg, uId, fId) => {
            // fromId(发送者) => uId(userId)  toId(接收者) => fId(friendId)
            try {
                // 将消息存数据库
                await socket_mongo.savePrivateChatMsg({ dataMsg, uId, fId })
                let data = {
                    userId: dataMsg.userId,
                    msgType: dataMsg.msgType,  // msgType 消息类型（0:文字（包括表情包），1:图片）
                    message: dataMsg.message,
                    time: new Date(),
                    fromId: uId,
                    toId: fId
                }
                socket.to(users[fId]).emit('private_chat', data)
                // 未读好友消息
                socket.to(users[fId]).emit('unread_message', uId)
            } catch (error) {
            }
        })

        // 进入群聊(join_group)
        socket.on('join_group', (gId) => {
            socket.join(gId)
        })

        // 群聊(group_chat)
        socket.on('group_chat', async (dataMsg, uId, gId) => {
            // fromId(发送者) => uId(userId)  toId(接收者) => gId(groupId)
            try {
                // 将消息存数据库
                let saveInfo = await socket_mongo.saveGroupChatMsg({ dataMsg, uId, gId })
                let messageId = saveInfo._id.toString() // 消息id
                // 将用户消息设置为未读  参数: 消息id 群id 发消息人的id
                await socket_mongo.groupMessageUnRead(messageId, gId, uId) // 不包含发送者
                // 查询群聊信息
                let info = await socket_mongo.findGroupInfo({ groupId: gId })
                let data = {
                    userId: dataMsg.userId, // 发消息好友信息
                    groupInfo: {
                        _id: info._id,
                        groupName: info.groupName,
                        imgUrl: info.imgUrl
                    }, // 群聊信息
                    msgType: dataMsg.msgType,  // msgType 消息类型（0:文字（包括表情包），1:图片）
                    message: dataMsg.message,
                    time: new Date(),
                    fromId: uId,
                    toId: gId
                }
                socket.to(gId).emit('group_chat', data)
                socket.to(gId).emit('unread_message', gId)
            } catch (error) {
            }
        })

        // 初始化申请消息通知
        socket.on('init_apply_notice', async (toId) => {
            // toId 接收方id
            let friendNoticeNum = await socket_mongo.friendNoticeNum(toId)
            let groupNoticeNum = await socket_mongo.groupNoticeNum(toId)
            socket.emit('init_apply_notice', { friendNoticeNum, groupNoticeNum })
        })

        // 好友、群申请通知
        socket.on('apply_notice', async (toId) => {
            // 好友申请消息
            let friendNoticeNum = await socket_mongo.friendNoticeNum(toId)
            // 入群申请消息
            let groupNoticeNum = await socket_mongo.groupNoticeNum(toId)
            socket.to(users[toId]).emit('apply_notice', { friendNoticeNum, groupNoticeNum })
        })

        // 同意好友/群申请
        socket.on('agree_apply', async (toId) => {
            // toId 接收方id
            socket.to(users[toId]).emit('agree_apply')
        })

        // 退出登陆
        socket.on('logout', () => {
            if (users.hasOwnProperty(socket.name)) {
                delete users[socket.name]
                num -= 1
                console.log('=============离开============');
                // console.log(socket.id,socket.name,'用户关闭连接')
                console.log('在线人数', num);
                // console.log(users);
                console.log('============================');
            }
        })

        socket.on('disconnect', function () {
            if (users.hasOwnProperty(socket.name)) {
                delete users[socket.name]
                num -= 1
                console.log('=============离开============');
                // console.log(socket.id,socket.name,'用户关闭连接')
                console.log('在线人数', num);
                // console.log(users);
                console.log('============================');
            }
            console.log('socket已断开')
        })
    })
}